package com.xxmw.transaction.controller.symbol;

import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.model.app.Symbol;
import com.xxmw.transaction.service.app.SymbolService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author luowenliang
 * @since 2020/4/10 09:26
 */
@RestController
@RequestMapping("/admin/symbol")
public class SymbolController {

    @Autowired
    private SymbolService symbolService;

    /**
     * 列表
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/list")
    @RequiresPermissions("symbol:list")
    public R list (@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                   @RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize,
                   @RequestParam(value = "name", required = false) String name) {
        return R.ok(symbolService.pageList(pageNum, pageSize, name));
    }

    /**
     * 下拉列表获取
     * @return
     */
    @GetMapping("/select")
    @RequiresPermissions("symbol:list")
    public R select () {
        return R.ok(symbolService.pageList(1, 10000, null).getRows());
    }

    /**
     * 新增
     * @return
     */
    @PostMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"symbol:save", "symbol:update"}, logical = Logical.OR)
    public R saveOrUpdate (Symbol symbol) {
        if (null == symbol.getBaseCurrency() || null == symbol.getQuoteCurrency()) {
            return R.error("币种名称不能为空");
        }
        symbol.setName(symbol.getBaseCurrency().toLowerCase() + symbol.getQuoteCurrency().toLowerCase());

        if (null == symbol.getId() || 0 == symbol.getId()) {
            if (symbolService.hasSymbol(symbol.getBaseCurrency(), symbol.getQuoteCurrency())) {
                return R.error("已有该交易对");
            }
            symbol.setId(null);
        }
        symbolService.saveOrUpdate(symbol);
        return R.ok();
    }

    /**
     * 获取所有报价币种
     * @return
     */
    @GetMapping("/quoteCurrency")
    public R quoteCurrency () {
        return R.ok(symbolService.quoteCurrency());
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @RequiresPermissions("symbol:delete")
    public R delete (@PathVariable Integer id) {
        symbolService.removeById(id);
        return R.ok();
    }
}
